<template>
    <el-dialog ref="dialogform" :title="addEditName + title" :visible.sync="dialogVisible"
        :width="addEditFlag == 'edit' ? '40%' : '90%'" :before-close="handleClose">
        <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="120px" class="demo-ruleForm">
            <template v-if="addEditFlag == 'add'">
                <el-form-item label="转出鱼塘" prop="sourceFishPondId">
                    <el-select v-model="ruleForm.sourceFishPondId" filterable clearable class="w100p"
                        @change="(e) => { handleChangeFishPond(e, 'sourceFishPondId') }">
                        <el-option :disabled="ruleForm.targetFishPondId == item.fishPondId"
                            v-for="(item, index) in fishPondList" :key="index" :label="item.pondName"
                            :value="item.fishPondId" />
                    </el-select>
                    <span class="errText" v-show="errText">{{ errText }}</span>
                </el-form-item>
                <el-form-item label="转出批次" prop="sourceBatchId">
                    <el-select v-model="ruleForm.sourceBatchId" filterable clearable class="w100p">
                        <el-option v-if="ruleForm.sourceFishPondId == item.fishPondId"
                            v-for="(item, index) in batchList" :key="index" :label="item.batchName"
                            :value="item.batchId" />
                    </el-select>
                </el-form-item>
                <el-form-item label="转入鱼塘" prop="targetFishPondId">
                    <el-select v-model="ruleForm.targetFishPondId" filterable clearable class="w100p"
                        @change="(e) => { handleChangeFishPond(e, 'targetFishPondId') }">
                        <el-option :disabled="ruleForm.sourceFishPondId == item.fishPondId"
                            v-for="(item, index) in fishPondList" :key="index" :label="item.pondName"
                            :value="item.fishPondId" />
                    </el-select>
                </el-form-item>
                <el-form-item label="转入批次" prop="targetBatchId">
                    <el-select v-model="ruleForm.targetBatchId" filterable clearable class="w100p">
                        <el-option v-if="ruleForm.targetFishPondId == item.fishPondId"
                            v-for="(item, index) in batchList" :key="index" :label="item.batchName"
                            :value="item.batchId" />
                    </el-select>
                </el-form-item>
            </template>
            <template v-if="addEditFlag == 'edit'">
                <el-form-item label="转出鱼塘" prop="sourceFishPondId">
                    <el-input disabled v-model="ruleForm.sourceFishPondName"></el-input>
                </el-form-item>
                <el-form-item label="转出批次" prop="sourceBatchId">
                    <el-input disabled v-model="ruleForm.sourceBatchName"></el-input>
                </el-form-item>
                <el-form-item label="转入鱼塘" prop="targetFishPondId">
                    <el-input disabled v-model="ruleForm.targetFishPondName"></el-input>
                </el-form-item>
                <el-form-item label="转入批次" prop="targetBatchId">
                    <el-input disabled v-model="ruleForm.targetBatchName"></el-input>
                </el-form-item>
                <el-form-item label="转入类型" prop="fishType">
                    <el-input disabled :placeholder="ruleForm.fishType == 'LIVE_FISH' ? '活鱼' : '次鱼'"
                        class="w100p"></el-input>
                </el-form-item>
                <el-form-item label="转出品种" prop="fishVarietyId">
                    <el-input disabled v-model="ruleForm.fishVarietyName"></el-input>
                </el-form-item>
                <el-form-item label="转出规格" prop="specificationId">
                    <el-select filterable clearable v-model="ruleForm.specificationId" placeholder="选择规格" class="w100p">
                        <el-option v-if="ruleForm.fishVarietyId == item.fishVarietyId"
                            v-for="item, index in specificationList" :key="index" :label="item.specificationName"
                            :value="item.specificationId" />
                    </el-select>
                </el-form-item>
                <el-form-item label="转出数量" prop="num">
                    <el-input v-model="ruleForm.num" clearable placeholder="请输入数量" type="number" class="w100p">
                        <template slot="append">尾</template>
                    </el-input>
                    <span class="errText" v-show="maxNum >= 0">{{ `系统记录在塘${maxNum}尾` }}</span>
                </el-form-item>
                <el-form-item label="转出重量" prop="weight">
                    <el-input v-model="ruleForm.weight" placeholder="请输入重量" clearable type="number" class="w100p">
                        <template slot="append">斤</template>
                    </el-input>
                </el-form-item>
            </template>
            <template v-if="addEditFlag == 'add'">
                <el-row v-for="detail, index in ruleForm.detailList" :key="index">
                    <el-col :span="4">
                        <el-form-item :label="index == 0 ? '转入类型' : ''" :prop="`detailList[${index}][fishType]`" :rules="rules.fishType">
                            <el-select v-model="detail.fishType" filterable clearable class="w100p">
                                <el-option label="活鱼" value="LIVE_FISH" />
                                <el-option label="次鱼" value="SECONDARY_FISH" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="4">
                        <el-form-item :label="index == 0 ? '转出品种' : ''" :prop="`detailList[${index}][fishVarietyId]`" :rules="rules.fishVarietyId">
                            <el-select v-model="detail.fishVarietyId" filterable clearable class="w100p"
                                @change="handleChangeFishVariety">
                                <el-option v-if="ruleForm.sourceFishPondId" v-for="item, index in fishVarietyList"
                                    :key="index" :label="item.fishVarietyName" :value="item.fishVarietyId" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="4">
                        <el-form-item :label="index == 0 ? '转出规格' : ''" :prop="`detailList[${index}][specificationId]`" :rules="rules.specificationId">
                            <el-select filterable clearable v-model="detail.specificationId" placeholder="选择规格"
                                class="w100p">
                                <el-option v-if="detail.fishVarietyId == item.fishVarietyId"
                                    v-for="item, index in specificationList" :key="index"
                                    :label="item.specificationName" :value="item.specificationId" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="5">
                        <el-form-item :label="index == 0 ? '转出数量' : ''" :prop="`detailList[${index}][num]`" :rules="rules.num">
                            <el-input v-model="detail.num" clearable placeholder="请输入数量" type="number" class="w100p">
                                <template slot="append">尾</template>
                            </el-input>
                            <span class="errText">{{ errTextObj[detail.fishVarietyId] }}</span>
                        </el-form-item>
                    </el-col>
                    <el-col :span="5">
                        <el-form-item :label="index == 0 ? '转出重量' : ''" :prop="`detailList[${index}][weight]`" :rules="rules.weight">
                            <el-input v-model="detail.weight" placeholder="请输入重量" clearable type="number" class="w100p">
                                <template slot="append">斤</template>
                            </el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="2">
                        <i class="icon el-icon-circle-plus-outline" @click.stop="addMaterial()"></i>
                        <i v-show="index" class="icon el-icon-remove-outline" @click.stop="delMaterial(index)"></i>
                    </el-col>
                </el-row>
            </template>
            <el-form-item label="操作人" prop="staffId">
                <el-select v-model="ruleForm.staffId" filterable clearable class="w100p" @change="handleChangeStaff">
                    <el-option v-for="item, index in staffList" :key="index" :label="item.staffName"
                        :value="item.staffId" />
                </el-select>
            </el-form-item>
            <el-form-item label="转塘日期" prop="recordDate">
                <el-date-picker v-model="ruleForm.recordDate" value-format="yyyy-MM-dd" type="date" placeholder="选择日期"
                    :picker-options="pickerOptions" class="w100p">
                </el-date-picker>
            </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
            <el-button @click="cancel">取 消</el-button>
            <SaveDraftBox ref="saveDraft" v-if="addEditFlag == 'add' && dialogVisible" :formData="ruleForm"
                @pushData="pushData">
            </SaveDraftBox>
            <el-button type="primary" @click="submitForm">确 定</el-button>
        </span>
    </el-dialog>
</template>
<script>
import pondTransferOperation from '@/api/production-management/pond-transfer-operation.js';
import pondStockingManagement from '@/api/production-management/pond-stocking-management.js';
// pond-transfer-operation
export default {
    components: {},
    props: {
        addEditFlag: {
            type: String,
            default: () => {
                return 'add'
            }
        },
        data: {
            type: Object,
            default: () => {
                return {}
            }
        },
        title: {
            type: String,
            default: () => {
                return '操作表单'
            }
        },
        dialogVisible: {
            type: Boolean,
            default: () => {
                return false
            }
        },
        fishPondList: {
            type: Array,
            default: () => {
                return []
            }
        },
        batchList: {
            type: Array,
            default: () => {
                return []
            }
        },
        specificationList: {
            type: Array,
            default: () => {
                return []
            }
        },
        staffList: {
            type: Array,
            default: () => {
                return []
            }
        },
    },
    data() {
        let checkNum = (rule, value, callback) => {
            if (value) {
                // let maxNum = this.maxNum > 0 ? this.maxNum : 99999
                // if (Number(value) > 0 && Number(value) <= 99999) {
                //     callback();
                // } else if (Number(value) > maxNum) {
                //     callback(new Error(`请输入小于${maxNum + 1}的数`));
                // } else {
                //     callback(new Error('请输入大于0的数'));
                // }
                if (Number(value) > 0 && Number(value) < 100000) {
                    callback();
                } else if (Number(value) > maxNum) {
                    callback(new Error(`请输入小于100000的数`));
                } else {
                    callback(new Error('请输入大于0的数'));
                }
            } else {
                callback(new Error('请输入数值'));
            }
        };
        return {
            pickerOptions: {
                disabledDate(time) {
                    return time.getTime() >= Date.now();
                },
                shortcuts: [{
                    text: '今天',
                    onClick(picker) {
                        picker.$emit('pick', new Date());
                    }
                }, {
                    text: '昨天',
                    onClick(picker) {
                        const date = new Date();
                        date.setTime(date.getTime() - 3600 * 1000 * 24);
                        picker.$emit('pick', date);
                    }
                }, {
                    text: '一周前',
                    onClick(picker) {
                        const date = new Date();
                        date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
                        picker.$emit('pick', date);
                    }
                }]
            },
            maxNum: -1,
            errText: '',
            errTextObj: {},
            fishVarietyList: [],
            fishVarietyNumObj: {},
            addEditName: '添加',
            addEditApi: '',
            ruleForm: {},
            rules: {
                batchId: [
                    { required: true, message: '请选择批次', trigger: 'change' }
                ],
                num: [
                    { required: true, validator: checkNum, trigger: 'change' }
                ],
                weight: [
                    { required: true, validator: checkNum, trigger: 'change' }
                ],
                recordDate: [
                    { required: true, message: '请选择称重时间', trigger: 'change' }
                ],
                targetFishPondId: [
                    { required: true, message: '请选择鱼塘', trigger: 'change' }
                ],
                targetBatchId: [
                    { required: true, message: '请选择批次', trigger: 'change' }
                ],
                sourceFishPondId: [
                    { required: true, message: '请选择鱼塘', trigger: 'change' }
                ],
                sourceBatchId: [
                    { required: true, message: '请选择批次', trigger: 'change' }
                ],
                staffId: [
                    { required: true, message: '请选择操作人', trigger: 'change' }
                ],
                fishVarietyId: [
                    { required: true, message: '请选择品种', trigger: 'change' }
                ],
                specificationId: [
                    { required: true, message: '请选择品种规格', trigger: 'change' }
                ],
                fishType: [
                    { required: true, message: '请选择类型', trigger: 'change' }
                ]
            }
        }
    },
    computed: {},
    watch: {
        dialogVisible(v) {
            v && this.initData()
        }
    },

    mounted() { },
    methods: {
        initData() {
            if (this.addEditFlag == 'add') {
                this.resetForm()
                this.addEditApi = pondTransferOperation.addMultiple
                this.addEditName = '添加';
                this.getInitRulFormData();
            } else if (this.addEditFlag == 'edit') {
                this.ruleForm = { ...this.data }
                this.addEditApi = pondTransferOperation.edit
                this.addEditName = '编辑';
                this.batchPondInfoList(this.data.sourceBatchId)
            }
        },
        pushData(data) {
            this.ruleForm = { ...data };
            this.$nextTick(() => {
                this.$refs.ruleForm.clearValidate();
            })
        },
        //通过批次id查询批次下的鱼种
        //转塘时需要对鱼种做限制
        async batchPondInfoList(batchId) {
            if (!batchId) {
                this.$set(this.ruleForm, 'fishVarietyId', '');
                this.$set(this.ruleForm, 'specificationId', '');
                this.$set(this.ruleForm, 'fishVarietyName', '');
                this.$set(this.ruleForm, 'weight', '');
                this.$set(this.ruleForm, 'num', '');
                this.errText = '';
                this.maxNum = -1;
                return
            }
            let { data: fishVarietyList } = await pondStockingManagement.batchPondInfoList({ batchId });
            this.fishVarietyList = fishVarietyList || [];
            this.fishVarietyNumObj = {}
            this.fishVarietyList = this.fishVarietyList.filter(item => {
                this.fishVarietyNumObj[item.fishVarietyId] = item.num
                return item.num > 0
            })
            this.errText = '';
            this.maxNum = -1;
            this.errTextObj = {};
            this.fishVarietyList.forEach((item, index) => {
                if (this.addEditFlag == 'edit') {
                    let editFishNum = 0;
                    if (this.ruleForm.fishVarietyId == item.fishVarietyId) {
                        editFishNum = item.num + this.ruleForm.num
                    } else {
                        editFishNum = item.num
                    }
                    this.errTextObj[item.fishVarietyId] = `${item.fishVarietyName}${editFishNum}尾`
                    this.errText += `${item.fishVarietyName}${editFishNum}尾${index + 1 == this.fishVarietyList.length ? "" : ";"}`
                } else {
                    this.errTextObj[item.fishVarietyId] = `${item.fishVarietyName}${item.num}尾`
                    this.errText += `${item.fishVarietyName}${item.num}尾${index + 1 == this.fishVarietyList.length ? "" : ";"}`
                }
            });
            console.log(this.errTextObj)
        },
        //初始化一些表单数据
        getInitRulFormData() {
            let id = sessionStorage.getItem('staffId') || null;
            let detailList = [{
                "fishType": "",
                "fishVarietyId": "",
                "fishVarietyName": "",
                "num": "",
                "specName": "",
                "specificationId": "",
                "weight": ""
            }]
            let params = {
                staffId: id == 'null' ? '' : Number(id),
                recordDate: this.$formatTime(new Date(), 'yyyy-MM-dd HH:mm:ss'),
                detailList: detailList
            }
            this.$set(this, 'ruleForm', params);
        },
        //添加明细
        addMaterial() {
            let length = this.ruleForm.detailList?.length || 0
            if (length) {
                this.$set(this.ruleForm.detailList, length, {
                    "fishType": "",
                    "fishVarietyId": "",
                    "fishVarietyName": "",
                    "num": "",
                    "specName": "",
                    "specificationId": "",
                    "weight": ""
                })
            }
        },
        //删除明细
        delMaterial(index) {
            let list = this.ruleForm.detailList;
            list.splice(index, 1);
            this.$set(this.ruleForm, 'detailList', list)
        },
        //选择鱼塘时提示用户是否存在该关联批次
        handleChangeFishPond(id, key) {
            let batchKey = '';
            let isQueryfishVarietyList = false
            if (key == 'targetFishPondId') {
                batchKey = 'targetBatchId'
                isQueryfishVarietyList = false
            } else if (key == 'sourceFishPondId') {
                batchKey = 'sourceBatchId';
                isQueryfishVarietyList = true;
            } else {
                return
            }
            let rut = this.batchList.find(item => item.fishPondId == id);
            let batchId = rut?.batchId
            this.$set(this.ruleForm, batchKey, batchId || '');
            !rut && this.$message.warning('该鱼塘暂无批次!');
            if (isQueryfishVarietyList) {
                this.batchPondInfoList(batchId);
            }
            if (this.ruleForm.detailList && this.ruleForm.detailList.length > 0) {
                this.ruleForm.detailList.forEach(item => {
                    for (let key in item) {
                        item[key] = ''
                    }
                })
            }
            this.$nextTick(() => {
                this.$refs['ruleForm'].clearValidate()
            })
        },
        //选择品种时提示用户是否存在该品种规格
        handleChangeFishVariety(id) {
            let rut = this.specificationList.find(item => item.fishVarietyId == id);
            let specificationId = rut?.specificationId;
            if (this.addEditFlag == 'edit') {
                this.maxNum = this.fishVarietyNumObj[id] + this.ruleForm.num;
            } else {
                this.maxNum = this.fishVarietyNumObj[id];
            }
            this.$set(this.ruleForm, 'specificationId', specificationId || '');
            !rut && this.$message.warning('该鱼种暂未配置规格!');
        },
        //获取姓名
        handleChangeStaff(id) {
            let rut = this.staffList.find(item => item.staffId == id);
            let staffName = rut?.staffName
            this.$set(this.ruleForm, 'staffName', staffName || '');
        },
        //提交表单
        submitForm() {
            this.$refs.ruleForm.validate((valid) => {
                if (valid) {
                    this.addEditApi({ ...this.ruleForm }).then(res => {
                        let msg = res.success ? '操作成功' : '操作失败'
                        this.$message[res.success ? 'success' : 'warning'](res.message || msg)
                        res.success && this.cancel();
                        res.success && this.addEditFlag == 'add' && this.$refs.saveDraft.delByKey();
                    }).catch(err => {
                        this.$message.error(err)
                    })
                } else {
                    return false;
                }
            })
        },
        //重置
        resetForm() {
            this.maxNum = -1;
            this.errText = '';
            this.ruleForm = {};
            this.$refs.ruleForm && this.$refs.ruleForm.resetFields()
        },
        //取消关闭
        cancel() {
            this.resetForm()
            this.$emit("closeDialog")
        },
        handleClose(done) {
            this.$confirm('确认关闭？')
                .then(_ => { this.resetForm(); this.cancel() })
                .catch(_ => { });
        }
    }
};
</script>
<style lang="scss" scoped>
.icon {
    font-size: 24px;
    line-height: 30px;
    margin-left: 15px;
}
</style>